package main

import (
	"fmt"
	"gorm.io/gorm"
	"time"
)

//	type ArticleModel struct {
//		ID    uint       `gorm:"type:uint"`
//		Title string     `gorm:"type:varchar(30)"`
//		Tag   []TagModel `gorm:"many2many:article_tags;joinForeignKey:ArticleID;JoinReferences:TagID"`
//	}
type TagModel struct {
	ID      uint           `gorm:"type:uint"`
	Name    string         `gorm:"type:varchar(20)"`
	Article []ArticleModel `gorm:"many2many:article_tags;joinForeignKey:TagID;JoinReferences:ArticleID"`
}
type ArticleTagModel struct {
	ArticleID uint      `gorm:"primaryKey"`
	TagID     uint      `gorm:"primaryKey"`
	CreatedAt time.Time `json:"created_at"`
}

func (b *ArticleTagModel) BeforeCreate(db *gorm.DB) error {
	b.CreatedAt = time.Now()
	return nil
}
func main() {
	DB.SetupJoinTable(&ArticleModel{}, "Tags", &ArticleTagModel{}) //自定义连接表 通过Article表查设置tag
	DB.SetupJoinTable(&TagModel{}, "Articles", &ArticleTagModel{}) //自定义连接表 通过tag表查设置article
	//DB.AutoMigrate(&ArticleModel{}, &TagModel{}, &ArticleTagModel{})
	DB = DB.Session(&gorm.Session{
		Logger: mysqlLogger,
	})
	//添加文章并添加标签
	//DB.Create(&ArticleModel{
	//	Title: "beego基础",
	//	Tag: []TagModel{
	//		{
	//			Name: "beego",
	//		},
	//		{
	//			Name: "框架",
	//		},
	//	},
	//})
	//查询
	var article []ArticleModel
	DB.Preload("Tag").Find(&article)
	fmt.Println(article)
}
